//
//  TableViewController.m
//  MVVMLearn
//
//  Created by 李旭阳[产品技术中心] on 2020/6/2.
//  Copyright © 2020 李旭阳[产品技术中心]. All rights reserved.
//

#import "TableViewController.h"
#import "YiRefreshHeader.h"
#import "TableViewModel.h"
#import "CustomModel.h"
#import "UIImageView+AFNetworking.h"
#import "IconViewModel.h"
#define kCustomRowCount 7

static NSString *reuseIdentifier = @"Cell";

@interface TableViewController () <UIScrollViewDelegate>


@property (strong, nonatomic) YiRefreshHeader *refreshHeader;
@property (strong, nonatomic) TableViewModel *tableViewModel;

@property (nonatomic, strong) NSMutableDictionary *imageDownloadsInProgress;

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}


- (void) setupUI{
    self.title = @"MVVMLearn";
    
    self.tableViewModel=[[TableViewModel alloc] init];
    self.entries=[[NSMutableArray alloc] init ];
    
    //    YiRefreshHeader  头部刷新按钮的使用  下啦刷新
    self.refreshHeader=[[YiRefreshHeader alloc] init];
    self.refreshHeader.scrollView=self.tableView;
    [self.refreshHeader header];
    __weak typeof(self) weakSelf = self;
    self.refreshHeader.beginRefreshingBlock=^(){
        __strong typeof(self) strongSelf = weakSelf;
        [strongSelf headerRefreshAction];
    };
    
    //    是否在进入该界面的时候就开始进入刷新状态
    [self.refreshHeader beginRefreshing];
    
}


- (void)headerRefreshAction
{
    [self.tableViewModel headerRefreshRequestWithCallback:^(NSArray *array){
        self.entries=array;
        [self.refreshHeader endRefreshing];
        [self.tableView reloadData];
    }];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSUInteger count = self.entries.count;
    
    // if there's no data yet, return enough rows to fill the screen
    if (count == 0)
    {
        return kCustomRowCount;
    }
    return count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSUInteger nodeCount = self.entries.count;
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
    }
    if (nodeCount > 0) {
        CustomModel *custmodel = (self.entries)[indexPath.row];
        cell.textLabel.text = [NSString stringWithFormat:@"%@",custmodel.albumId];
        cell.detailTextLabel.text =custmodel.title;
        if (!custmodel.thumbnailIcon) {
            if (self.tableView.dragging == NO && self.tableView.decelerating == NO) {
                
                //下载图片
                [self startIconDownload:custmodel forIndexPath:indexPath];
            }
            
            // if a download is deferred or in progress, return a placeholder image
            cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
        }else{
            
            //展示下载好的图片
            cell.imageView.image  = custmodel.thumbnailIcon;
        }
        
        
    }
    
    
    return cell;
}



#pragma mark - Table cell image support

// -------------------------------------------------------------------------------
//    startIconDownload:forIndexPath:
// -------------------------------------------------------------------------------
- (void)startIconDownload:(CustomModel *)custmodel forIndexPath:(NSIndexPath *)indexPath
{
    IconViewModel *iconDownloader = (self.imageDownloadsInProgress)[indexPath];
    if (iconDownloader == nil) {
        iconDownloader = [[IconViewModel alloc] init];
        iconDownloader.customModel =custmodel;
        [iconDownloader setCompletionHandler:^{
            UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.imageView.image = custmodel.thumbnailIcon;
            [self.imageDownloadsInProgress removeObjectForKey:indexPath];
        }];
        (self.imageDownloadsInProgress)[indexPath]  = iconDownloader;
        [iconDownloader startDownload];
    }
    
}


// -------------------------------------------------------------------------------
//    loadImagesForOnscreenRows
//  This method is used in case the user scrolled into a set of cells that don't
//  have their app icons yet.
// -------------------------------------------------------------------------------
- (void)loadImagesForOnscreenRows
{
    if (self.entries.count > 0)
    {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            CustomModel *customModel = (self.entries)[indexPath.row];
            
            if (!customModel.thumbnailIcon)
                // Avoid the app icon download if the app already has an icon
            {
                [self startIconDownload:customModel forIndexPath:indexPath];
            }
        }
    }
}



//点击事件，重要的是 要页面跳转，以及信息传递
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    
    [self showSimpleAlert:cell.textLabel.text and:cell.detailTextLabel.text];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


// Show an alert with an "Okay" button.
- (void)showSimpleAlert:(NSString *) textLabel and:(NSString *) detailTextLabel {
    
    if (textLabel != nil&& detailTextLabel !=nil) {
        NSString *title =textLabel;
        NSString *message =detailTextLabel;
        NSString *cancelButtonTitle = @"OK";
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        //增加确定按钮；
        [alertController addAction:[UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            
        }]];
        
        [self presentViewController:alertController animated:true completion:nil];
    }
    
    
    
}


#pragma mark - UIScrollViewDelegate

// -------------------------------------------------------------------------------
//    scrollViewDidEndDragging:willDecelerate:
//  Load images for all onscreen rows when scrolling is finished.
// -------------------------------------------------------------------------------
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        [self loadImagesForOnscreenRows];
    }
}

// -------------------------------------------------------------------------------
//    scrollViewDidEndDecelerating:scrollView
//  When scrolling stops, proceed to load the app icons that are on screen.
// -------------------------------------------------------------------------------
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
    
}



@end
